﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Resources;
using WeatherCN_Phone.Infrastructure;
using WeatherCN_Phone.Models;
using WeatherCN_Phone.WeatherCNData;
using System.Windows.Input;
using WeatherCN_Phone.ViewModels;
using System.Collections.ObjectModel;
using System.Windows.Media;

namespace WeatherCN_Phone
{
    //MainPage的ViewModel
    public class MainViewModel : INotifyPropertyChanged
    {
        public MainViewModel()
        {
            this.WeatherInfo = new WeatherInfo_Converted();
        }

        public int? selectIndex = null;

        private bool _IsLoading;
        public bool IsLoading
        {
            get
            {
                return _IsLoading;
            }
            set
            {
                if (value != _IsLoading)
                {
                    _IsLoading = value;
                    NotifyPropertyChanged("IsLoading");
                }
            }
        }
        private Visibility _WeatherInfoPanelVisibility;
        public Visibility WeatherInfoPanelVisibility
        {
            get
            {
                return _WeatherInfoPanelVisibility;
            }
            set
            {
                if (value != _WeatherInfoPanelVisibility)
                {
                    _WeatherInfoPanelVisibility = value;
                    NotifyPropertyChanged("WeatherInfoPanelVisibility");
                }
            }
        }
        //纪录MainViewModel的数据是否已初始化
        public bool IsDataLoaded
        {
            get;
            private set;
        }
        //存储从数据缓存服务器返回的天气信息
        private WeatherInfo_Converted  _weatherinfo;
        public WeatherInfo_Converted WeatherInfo
        {
            get
            {
                return _weatherinfo;
            }
            set
            {
                if (value != _weatherinfo)
                {
                    _weatherinfo = value;
                    NotifyPropertyChanged("WeatherInfo");
                }
            }
        }
        //存储用户设定的主题名称（出于激活/使用状态的主题）
        private string _CurrentTheme;
        public string CurrentTheme
        {
            get
            {
                return _CurrentTheme;
            }
            set
            {
                if (value != _CurrentTheme)
                {
                    _CurrentTheme = value;
                    NotifyPropertyChanged("CurrentTheme");
                    NotifyPropertyChanged("WeatherInfo");//即时变更主题
                }
            }
        }

        private ObservableCollection<ThemeConfig> _ThemeConfigList;
        public ObservableCollection<ThemeConfig> ThemeConfigList 
        { 
            get
            {
                if (_ThemeConfigList == null)
                    _ThemeConfigList = new ObservableCollection<ThemeConfig>();
                return _ThemeConfigList;
            }
            set
            {
                if (value != _ThemeConfigList)
                {
                    _ThemeConfigList = value;
                    NotifyPropertyChanged("ThemeConfigList");
                }
            }
        }
        private ObservableCollection<FavoriteItem> _FavoriteItemList;
        public ObservableCollection<FavoriteItem> FavoriteItemList
        {
            get
            {
                if (_FavoriteItemList == null)
                    _FavoriteItemList = new ObservableCollection<FavoriteItem>();
                return _FavoriteItemList;
            }
            set
            {
                if (value != _FavoriteItemList)
                {
                    _FavoriteItemList = value;
                    NotifyPropertyChanged("FavoriteItemList");
                }
            }
        }

        //存储城市名和城市编号映射关系的List
        public List<CityIDMapping> ListCity;
        //LongListSelector控件的数据源
        private IEnumerable<GroupingLayer<string, CityIDMapping>> _longlistitems;
        public IEnumerable<GroupingLayer<string, CityIDMapping>> LongListItems
        {
            get
            {
                return _longlistitems;
            }
            set
            {
                if (value != _longlistitems)
                {
                    _longlistitems = value;
                    NotifyPropertyChanged("LongListItems");
                }
            }
        }

        public int CurrentPanoramaItemSelectIndex = 0;
        private ICommand _SetCurrentPanoramaItemNameCommand;
        public ICommand SetCurrentPanoramaItemNameCommand
        {
            get
            {
                if (_SetCurrentPanoramaItemNameCommand == null) _SetCurrentPanoramaItemNameCommand = new DelegateCommand(SetCurrentPanoramaItemSelectIndex, CanExecute);
                return _SetCurrentPanoramaItemNameCommand;
            }
        }

        private ICommand _GetSpecificWeatherInfoCommand;
        public ICommand GetSpecificWeatherInfoCommand
        {
            get
            {
                if (_GetSpecificWeatherInfoCommand == null) _GetSpecificWeatherInfoCommand = new DelegateCommand(GetSpecificWeatherInfo, CanExecute);
                return _GetSpecificWeatherInfoCommand;
            }
        }

        private ICommand _SetThemeCommand;
        public ICommand SetThemeCommand
        {
            get
            {
                if (_SetThemeCommand == null) _SetThemeCommand = new DelegateCommand(SetTheme, CanExecute);
                return _SetThemeCommand;
            }
        }

        private ICommand _SetFavoriteColorCommand;
        public ICommand SetFavoriteColorCommand
        {
            get
            {
                if (_SetFavoriteColorCommand == null) _SetFavoriteColorCommand = new DelegateCommand(SetFavoriteColor, CanExecute);
                return _SetFavoriteColorCommand;
            }
        }

        private ICommand _DelFavCommand;
        public ICommand DelFavCommand
        {
            get
            {
                if (_DelFavCommand == null) _DelFavCommand = new DelegateCommand(DelFav, CanExecute);
                return _DelFavCommand;
            }
        }

        private ICommand _AddFavCommand;
        public ICommand AddFavCommand
        {
            get
            {
                if (_AddFavCommand == null) _AddFavCommand = new DelegateCommand(AddFav, CanExecute);
                return _AddFavCommand;
            }
        }

        //初始化数据
        public void LoadData()
        {
            XMLProcessor.InitialConfig();//初始化独立存储中的设定档
            CurrentTheme = XMLProcessor.ReadCurrentTheme();//读取用户设定的主题名称（出于激活/使用状态的主题）
            InitialThemeList();
            InitialFavoriteItemList();
            //读取城市名与城市编码的映射信息
            ListCity = CityIDMappingProcessor.GetCityIDMappingList();
            //处理ListCity（根据Scope字段分组）以产生适合LongListSelector使用的数据源
            var selected = from c in ListCity group c by c.Scope into n select new GroupingLayer<string, CityIDMapping>(n);
            LongListItems = selected;
            
            this.IsDataLoaded = true;
        }


        //使用QQ IP地址服务得到当前用户的地理信息并根据地理信息向数据缓存服务器请求对应的天气信息
        //GetWeatherInfoByCityID("101010100");
        public void GetlocalCityName()
        {
            IsLoading = true;
            WeatherInfoPanelVisibility = Visibility.Collapsed;
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://fw.qq.com:80/ipaddress");
            RequestState myRequestState = new RequestState();
            myRequestState.request = myHttpWebRequest;
            myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
        }
        //因为QQ IP判定服务返回的结果是gb2312编码，Phone7不能处理需要使用Base64编码后发予数据缓存服务器处理。
        private static void RespCallback(IAsyncResult asynchronousResult)
        {
            RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
            HttpWebRequest myHttpWebRequest = myRequestState.request;
            myRequestState.response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult);

            Stream responseStream = myRequestState.response.GetResponseStream();

            byte[] buff = new byte[responseStream.Length];
            responseStream.Read(buff, 0, buff.Length);
            string strParam = Convert.ToBase64String(buff);
            WeatherCNData.DataSoapClient wc = new WeatherCNData.DataSoapClient();
            wc.GetLocalCityNameCompleted += new EventHandler<WeatherCNData.GetLocalCityNameCompletedEventArgs>(wc_GetLocalCityNameCompleted);
            wc.GetLocalCityNameAsync(strParam);
        }
        //收到经过数据缓存服务器转为utf8编码的城市名称，根据城市名称从ListCity中取得对应的城市编号后向数据缓存服务器请求该编号的天气信息
        static void wc_GetLocalCityNameCompleted(object sender, WeatherCNData.GetLocalCityNameCompletedEventArgs e)
        {
            App.ViewModel.WeatherInfo.city = e.Result;
            var cityid = from p in App.ViewModel.ListCity where p.CityName == e.Result select p.CityID;
            if (e.Result == string.Empty || cityid.Count() == 0)
            {
                App.ViewModel.IsLoading = false;
                MessageBox.Show("We can't detect the city name or region that you stay now,Or you are not in China. You need to choose the city or region manualy.");
            }
            else
            {
                App.ViewModel.GetWeatherInfoByCityID(cityid.First());
            }
        }

        private void GetWeatherInfoByCityID(string aCityID)
        {
            DataSoapClient wc = new DataSoapClient();
            wc.GetWeatherInfoByCityIDCompleted += new EventHandler<GetWeatherInfoByCityIDCompletedEventArgs>(wc_GetWeatherInfoByCityIDCompleted);
            wc.GetWeatherInfoByCityIDAsync(aCityID);
        }
        //取得从数据缓存服务器返回的天气信息，并将其赋值给MainViewModel的WeatherInfo对象。
        void wc_GetWeatherInfoByCityIDCompleted(object sender, GetWeatherInfoByCityIDCompletedEventArgs e)
        {
            if (e.Result.cityid != null)
            {
                WeatherInfoPanelVisibility = Visibility.Visible;
                this.WeatherInfo = e.Result;
                IsLoading = false;
            }
            else
            {
                this.WeatherInfo = new WeatherInfo_Converted();
                IsLoading = false;
                MessageBox.Show("WeatherCN can't access the weather info belongs to the city or region that you selected.Please choose the nearest city or region and try again.");
            }
        }


        private void GetSpecificWeatherInfo(object parameter)
        {
            if (parameter != null)
            {
                WeatherInfo = new WeatherInfo_Converted();
                GetWeatherInfoByCityID(parameter.ToString());
                IsLoading = true;
                WeatherInfoPanelVisibility = Visibility.Collapsed;
            }
        }

        private void SetCurrentPanoramaItemSelectIndex(object parameter)
        {
            if (parameter != null)
            {
                this.CurrentPanoramaItemSelectIndex =(int) parameter;
            }
        }

        private void SetTheme(object parameter)
        {
            if (parameter != null && parameter.ToString()!=string.Empty)
            {
                XMLProcessor.SetCurrentTheme(parameter.ToString());
                CurrentTheme = XMLProcessor.ReadCurrentTheme();
                InitialThemeList();
            }
        }

        private void SetFavoriteColor(object parameter)
        {
            if (parameter != null && parameter.ToString()!=string.Empty)
            {
                XMLProcessor.SetFavoriteColor(parameter.ToString());
                InitialFavoriteItemList();
            }
        }

        private void DelFav(object parameter)
        {
            if (parameter != null && parameter.ToString() != string.Empty)
            {
                XMLProcessor.DelFav(parameter.ToString());
                InitialFavoriteItemList();
            }
        }

        private void AddFav(object parameter)
        {
            if (parameter != null && parameter.ToString() != string.Empty)
            {
                var cityname = from p in App.ViewModel.ListCity where p.CityID == parameter.ToString() select p.CityName;
                XMLProcessor.AddFav(parameter.ToString(),cityname.First());
                InitialFavoriteItemList();
            }
        }

        private bool CanExecute(object parameter)
        {
            return true;
        }

        private void InitialThemeList()
        {
            ThemeConfigList.Clear();
            foreach (string tpstr in XMLProcessor.GetThemeList())
            {
                ThemeConfigList.Add(new ThemeConfig() { ThemeName = tpstr });
            }
        }

        private void InitialFavoriteItemList()
        {
            FavoriteItemList.Clear();
            foreach (FavoriteItem tp in XMLProcessor.GetFavoriteItemList())
            {
                FavoriteItemList.Add(new FavoriteItem() { CityID = tp.CityID,CityName=tp.CityName,bgColor=tp.bgColor });
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}